package models

import (
	"time"

	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

type Department struct {
	Id           int64
	Name         string
	CreatedAt    int64
	FullName     string //店全名用于打印抬头
	Telephone    string //联系电话
	Address      string //联系地址
	Shopowner    string //店长姓名
	ShopownerTel string //店长电话
	Remarks      string
}

func (a *Department) TableName() string {
	return DepartmentTableName()
}

func DepartmentTableName() string {
	return TableName("department")
}

//获取部门列表
func DepartmentDataList(query_deps ...interface{}) []*Department {
	query := orm.NewOrm().QueryTable(DepartmentTableName())
	data := make([]*Department, 0)

	if len(query_deps) > 0 {
		query = query.Filter("id__in", query_deps...)
	}

	query.OrderBy("-id").All(&data)
	return data
}

/**
* 添加部门
 */
func DepartmentAdd(a *Department) (int64, error) {
	a.CreatedAt = time.Now().Unix()

	return orm.NewOrm().Insert(a)
}

//修改部门
func (a *Department) DepartmentEdit(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

//单条修改查询
func GetDepartmentById(id int64) (*Department, error) {
	r := new(Department)
	r.Id = id
	err := orm.NewOrm().Read(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//删除部门
func DepartmentDeleteById(id int64) error {
	o := orm.NewOrm().QueryTable(DepartmentTableName())
	if _, err := o.Filter("id", id).Delete(); err != nil {
		return err
	}
	return nil
}

//获取某一部门并将其缓存
func DepartmentCacheById(depid int64) (*Department, error) {
	cacheKey := fmt.Sprintf("wxb_department_one_%d", depid);
	dep := new(Department)
	if err := utils.GetCache(cacheKey, dep); err == nil {
		return dep, nil
	}
	o := orm.NewOrm().QueryTable(DepartmentTableName()).Filter("id", depid)
	if err := o.One(dep); err != nil {
		return nil, err;
	}
	//s, err := json.Marshal(dep)
	//if err != nil {
	//	return nil, err;
	//}

	if err := utils.SetCache(cacheKey, dep, 5000); err != nil {
		return nil, nil
	}

	return dep, nil;
}
